<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="JinYan&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
    <link rel="shortcut icon" href="/blog/css/images/logo.jpg">
  
  <title>
    
      Python-3-列表 | SanYuanEmpire
    
  </title>
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/blog/css/style.css">
<link rel="stylesheet" href="/blog/css/plugins/gitment.css">
  <script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js"></script>
  <script src="/blog/js/qrious.js"></script>
<script src="/blog/js/gitment.js"></script>
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


</head>
<div class="wechat-share">
  <img src="/css/images/logo.jpg" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/blog/">
      <div class="logo"></div>
      <span>SanYuanEmpire</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/blog/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/blog/archives/" class="item-link">Archives</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/blog/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/blog/archives/" class="menu-link">Archives</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>Python-3-列表</h2>
  <p class="post-date">2018-08-30</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="列表-list"><a href="#列表-list" class="headerlink" title="列表(list)"></a>列表(list)</h1><blockquote>
<p>列表是一种无序的、可重复的数据序列，可以随时添加、删除其中的元素。<br>列表页的每个元素都分配一个数字索引，从 0 开始<br>列表使用方括号创建，使用逗号分隔元素<br>列表元素值可以是任意类型，包括变量<br>使用方括号对列表进行元素访问、切片、修改、删除等操作，开闭合区间为[)形式<br>列表的元素访问可以嵌套<br>方括号内可以是任意表达式</p>
</blockquote>
<h1 id="创建列表"><a href="#创建列表" class="headerlink" title="创建列表"></a>创建列表</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">hello = (1, 2, 3)</span><br><span class="line">li = [1, &quot;2&quot;, [3, &apos;a&apos;], (1, 3), hello]</span><br><span class="line">访问元素</span><br><span class="line">li = [1, &quot;2&quot;, [3, &apos;a&apos;], (1, 3)]</span><br><span class="line">print(li[3]) # (1, 3)</span><br><span class="line">print(li[-2]) # [3, &apos;a&apos;]</span><br></pre></td></tr></table></figure>
<h1 id="切片访问"><a href="#切片访问" class="headerlink" title="切片访问"></a>切片访问</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">格式: list_name[begin:end:step] begin 表示起始位置(默认为0)，end 表示结束位置(默认为最后一个元素)，step 表示步长(默认为1)</span><br><span class="line">hello = (1, 2, 3)</span><br><span class="line">li = [1, &quot;2&quot;, [3, &apos;a&apos;], (1, 3), hello]</span><br><span class="line">print(li) # [1, &apos;2&apos;, [3, &apos;a&apos;], (1, 3), (1, 2, 3)]</span><br><span class="line">print(li[1:2]) # [&apos;2&apos;]</span><br><span class="line">print(li[:2]) # [1, &apos;2&apos;]</span><br><span class="line">print(li[:]) # [1, &apos;2&apos;, [3, &apos;a&apos;], (1, 3), (1, 2, 3)]</span><br><span class="line">print(li[2:]) # [[3, &apos;a&apos;], (1, 3), (1, 2, 3)]</span><br><span class="line">print(li[1:-1:2]) # [&apos;2&apos;, (1, 3)]</span><br></pre></td></tr></table></figure>
<h2 id="访问内嵌-list-的元素"><a href="#访问内嵌-list-的元素" class="headerlink" title="访问内嵌 list 的元素"></a>访问内嵌 list 的元素</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">li = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, [&apos;a&apos;, &apos;b&apos;, &apos;c&apos;]]</span><br><span class="line">print(li[1:-1:2][1:3]) # (3, 5)</span><br><span class="line">print(li[-1][1:3]) # [&apos;b&apos;, &apos;c&apos;]</span><br><span class="line">print(li[-1][1]) # b</span><br></pre></td></tr></table></figure>
<h1 id="修改列表"><a href="#修改列表" class="headerlink" title="修改列表"></a>修改列表</h1><blockquote>
<p>通过使用方括号，可以非常灵活的对列表的元素进行修改、替换、删除等操作。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">li = [0, 1, 2, 3, 4, 5]</span><br><span class="line">li[len(li) - 2] = 22 # 修改 [0, 1, 2, 22, 4, 5]</span><br><span class="line">li[3] = 33 # 修改 [0, 1, 2, 33, 4, 5]</span><br><span class="line">li[1:-1] = [9, 9] # 替换 [0, 9, 9, 5]</span><br><span class="line">li[1:-1] = [] # 删除 [0, 5]</span><br></pre></td></tr></table></figure></p>
</blockquote>
<h1 id="删除元素"><a href="#删除元素" class="headerlink" title="删除元素"></a>删除元素</h1><blockquote>
<p>可以用 del 语句来删除列表的指定范围的元素。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">li = [0, 1, 2, 3, 4, 5]</span><br><span class="line">del li[3] # [0, 1, 2, 4, 5]</span><br><span class="line">del li[2:-1] # [0, 1, 5]</span><br></pre></td></tr></table></figure></p>
</blockquote>
<h1 id="列表操作符"><a href="#列表操作符" class="headerlink" title="列表操作符"></a>列表操作符</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">+ 用于合并列表</span><br><span class="line">* 用于重复列表元素</span><br><span class="line">in 用于判断元素是否存在于列表中</span><br><span class="line">for ... in ... 用于遍历列表元素</span><br><span class="line">[1, 2, 3] + [3, 4, 5] # [1, 2, 3, 3, 4, 5]</span><br><span class="line">[1, 2, 3] * 2 # [1, 2, 3, 1, 2, 3]</span><br><span class="line">3 in [1, 2, 3] # True</span><br><span class="line">for x in [1, 2, 3]: print(x) # 1 2 3</span><br></pre></td></tr></table></figure>
<h1 id="列表函数"><a href="#列表函数" class="headerlink" title="列表函数"></a>列表函数</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">len(list) 列表元素个数</span><br><span class="line">max(list) 列表元素中的最大值</span><br><span class="line">min(list) 列表元素中的最小值</span><br><span class="line">list(seq) 将元组转换为列表</span><br><span class="line">li = [0, 1, 5]</span><br><span class="line">max(li) # 5</span><br><span class="line">len(li) # 3</span><br></pre></td></tr></table></figure>
<blockquote>
<p>注: 对列表使用 max/min 函数，2.x 中对元素值类型无要求，3.x 则要求元素值类型必须一致。</p>
</blockquote>
<h1 id="列表方法"><a href="#列表方法" class="headerlink" title="列表方法"></a>列表方法</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">list.append(obj)</span><br><span class="line">在列表末尾添加新的对象</span><br><span class="line">list.count(obj)</span><br><span class="line">返回元素在列表中出现的次数</span><br><span class="line">list.extend(seq)</span><br><span class="line">在列表末尾一次性追加另一个序列中的多个值</span><br><span class="line">list.index(obj)</span><br><span class="line">返回查找对象的索引位置，如果没有找到对象则抛出异常</span><br><span class="line">list.insert(index, obj)</span><br><span class="line">将指定对象插入列表的指定位置</span><br><span class="line">list.pop([index=-1]])</span><br><span class="line">移除列表中的一个元素（默认最后一个元素），并且返回该元素的值</span><br><span class="line">list.remove(obj)</span><br><span class="line">移除列表中某个值的第一个匹配项</span><br><span class="line">list.reverse()</span><br><span class="line">反向排序列表的元素</span><br><span class="line">list.sort(cmp=None, key=None, reverse=False)</span><br><span class="line">对原列表进行排序，如果指定参数，则使用比较函数指定的比较函数</span><br><span class="line">list.clear()</span><br><span class="line">清空列表 还可以使用 del list[:]、li = [] 等方式实现</span><br><span class="line">list.copy()</span><br><span class="line">复制列表 默认使用等号赋值给另一个变量，实际上是引用列表变量。如果要实现</span><br></pre></td></tr></table></figure>
<h1 id="列表推导式"><a href="#列表推导式" class="headerlink" title="列表推导式"></a>列表推导式</h1><blockquote>
<p>列表推导式提供了从序列创建列表的简单途径。通常应用程序将一些操作应用于某个序列的每个元素，用其获得的结果作为生成新列表的元素，或者根据确定的判定条件创建子序列。<br>每个列表推导式都在 for 之后跟一个表达式，然后有零到多个 for 或 if 子句。返回结果是一个根据表达从其后的 for 和 if 上下文环境中生成出来的列表。如果希望表达式推导出一个元组，就必须使用括号。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">将列表中每个数值乘三，获得一个新的列表：</span><br><span class="line">vec = [2, 4, 6]</span><br><span class="line">[(x, x**2) for x in vec]</span><br><span class="line"># [(2, 4), (4, 16), (6, 36)]</span><br><span class="line">对序列里每一个元素逐个调用某方法：</span><br><span class="line">freshfruit = [&apos; banana&apos;, &apos; loganberry &apos;, &apos;passion fruit &apos;]</span><br><span class="line">[weapon.strip() for weapon in freshfruit]</span><br><span class="line"># [&apos;banana&apos;, &apos;loganberry&apos;, &apos;passion fruit&apos;]</span><br><span class="line">用 if 子句作为过滤器：</span><br><span class="line">vec = [2, 4, 6]</span><br><span class="line">[3*x for x in vec if x &gt; 3]</span><br><span class="line"># [12, 18]vec1 = [2, 4, 6]</span><br><span class="line">vec2 = [4, 3, -9]</span><br><span class="line">[x*y for x in vec1 for y in vec2]</span><br><span class="line"># [8, 6, -18, 16, 12, -36, 24, 18, -54]</span><br><span class="line">[vec1[i]*vec2[i] for i in range(len(vec1))]</span><br><span class="line"># [8, 12, -54]</span><br><span class="line">列表嵌套解析：</span><br><span class="line">matrix = [</span><br><span class="line">[1, 2, 3],</span><br><span class="line">[4, 5, 6],</span><br><span class="line">[7, 8, 9],</span><br><span class="line">]</span><br><span class="line">new_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]</span><br><span class="line">print(new_matrix)</span><br><span class="line"># [[1, 4, 7], [2, 5, 8], [3, 6, 9]]</span><br></pre></td></tr></table></figure></p>
</blockquote>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/blog/2018/08/30/Python-3-字符串/">
        <span class="nav-arrow">← </span>
        
          Python-3-字符串
        
      </a>
    
    
      <a class="nav-right" href="/blog/2018/08/30/Python-3-元组/">
        
          Python-3-元组
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    
      <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#列表-list"><span class="toc-nav-text">列表(list)</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#创建列表"><span class="toc-nav-text">创建列表</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#切片访问"><span class="toc-nav-text">切片访问</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#访问内嵌-list-的元素"><span class="toc-nav-text">访问内嵌 list 的元素</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#修改列表"><span class="toc-nav-text">修改列表</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#删除元素"><span class="toc-nav-text">删除元素</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#列表操作符"><span class="toc-nav-text">列表操作符</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#列表函数"><span class="toc-nav-text">列表函数</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#列表方法"><span class="toc-nav-text">列表方法</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#列表推导式"><span class="toc-nav-text">列表推导式</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'git@gitee.com:sanyuanempire/blog.git/2018/08/30/Python-3-列表/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

     // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()
        
        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })

    // qrcode
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });

    // gitment
    var gitmentConfig = "";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "Python-3-列表",
        owner: "",
        repo: "",
        oauth: {
          client_id: "",
          client_secret: ""
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  })();
</script>

<script>
  var disqus_shortname = '';
  
  var disqus_url = 'git@gitee.com:sanyuanempire/blog.git/2018/08/30/Python-3-列表/';
  
  (function(){
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = '//go.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
  })();
</script>

    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2018 | Proudly powered by <a href="https://sanyuanempire.gitee.io/blog" target="_blank">JinYan</a>
    <br>
    Theme by <a href="https://sanyuanempire.gitee.io/blog">JinYan</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->

<script src="/blog/js/script.js"></script>

  </body>
</html>